import socket
import sys

addr = None
port = None
listen_port = int(sys.argv[1])

sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.bind(('', listen_port))

while True:
	data, address = sock.recvfrom(8192)

	if address[0] == '127.0.0.1':
		print 'receive from server:', repr(data), address
		port = address[1]
		sock.sendto(data, addr)
	else:
                print 'receive from agent:', repr(data), address
		if data[0] != '\x02': 
			sock.sendto(data, ('localhost', port))
		else:
			print 'ID', ord(data[1])
		addr = address
	
sock.close()
